﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using SpImageCasheSDK;

namespace SpImageCacheActions
{
    class SpImageCacheScaleAction : ISpImageCacheAction
    {
        public Image Execute(Image image, params object[] actionParameters)
        {
            int width = -1;

            int height = -1;

            bool widthInPixel = true;

            bool heightInPixel = true;

            try
            {
                if (actionParameters.Length > 0)
                {
                    if (actionParameters[0].ToString().EndsWith("%")) widthInPixel = false;

                    width = int.Parse(((string)actionParameters[0]).Trim().TrimEnd('%', 'p', 'x'));
                }

                if (actionParameters.Length > 1)
                {
                    if (actionParameters[1].ToString().EndsWith("%")) heightInPixel = false;

                    height = int.Parse(((string)actionParameters[1]).Trim().TrimEnd(' ', '%', 'p', 'x'));
                }
            }
            catch (ArgumentNullException)
            {

            }
            catch (FormatException)
            {

            }
            catch (OverflowException)
            {

            }

            if (width == -1)
                width = image.Width;

            if (height == -1)
                height = image.Height;

            return ResizeImage(image, new Size(widthInPixel ? width : (int)(image.Width * ((float)width / 100)), heightInPixel ? height : (int)(image.Height * ((float)height / 100))));
        }

        private static Image ResizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;

            int sourceHeight = imgToResize.Height;

            float nPercentW = (size.Width / (float)sourceWidth);

            float nPercentH = (size.Height / (float)sourceHeight);

            float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);

            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);

            Graphics g = Graphics.FromImage(b);

            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);

            g.Dispose();

            return b;
        }
    }
}
